package com.example.duihua.service.impl;

import com.example.duihua.entity.Conversation;
import com.example.duihua.mapper.ConversationMapper;
import com.example.duihua.service.ConversationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ConversationServiceImpl implements ConversationService {

    @Autowired
    private ConversationMapper conversationMapper;

    @Override
    public List<Conversation> getUserConversations(Long userId) {
        return conversationMapper.findByUserId(userId);
    }

    @Override
    public Conversation saveOrUpdate(Conversation conversation) {
        Conversation existing = conversationMapper.findByIdAndUserId(conversation.getId(), conversation.getUserId());
        if (existing == null) {
            conversationMapper.insert(conversation);
        } else {
            conversationMapper.update(conversation);
        }
        return conversation;
    }

    @Override
    public Conversation findByIdAndUserId(String id, Long userId) {
        return conversationMapper.findByIdAndUserId(id, userId);
    }

    @Override
    public Conversation findPrivateConversation(Long userId, Long targetId) {
        // 构建私聊会话ID
        Long smallerId = Math.min(userId, targetId);
        Long largerId = Math.max(userId, targetId);
        String conversationId = smallerId + "_" + largerId;
        
        // 查找会话
        Conversation conversation = conversationMapper.findByIdAndUserId(conversationId, userId);
        
        // 如果会话不存在，返回null
        return conversation;
    }

    @Override
    public Conversation findGroupConversation(Long userId, Long groupId) {
        // 构建群聊会话ID
        String conversationId = "group_" + groupId;
        
        // 查找会话
        return conversationMapper.findByIdAndUserId(conversationId, userId);
    }

    @Override
    public boolean deleteConversation(String id, Long userId) {
        // 先检查会话是否存在且属于该用户
        Conversation conversation = conversationMapper.findByIdAndUserId(id, userId);
        if (conversation == null) {
            return false;
        }
        
        // 执行删除操作
        return conversationMapper.delete(id, userId) > 0;
    }

    @Override
    public boolean updateUnreadCount(String id, Long userId, int count) {
        return conversationMapper.updateUnreadCount(id, userId, count) > 0;
    }

    @Override
    public boolean resetUnreadCount(String id, Long userId) {
        return conversationMapper.resetUnreadCount(id, userId) > 0;
    }
}
